/**
 * Created by chenxq on 2017/12/8.
 */
import { routerRedux } from 'dva/router';
import {customerApi} from './../services/api';

export default {
  namespace: 'customer',
  state: {
    list:[],
    curInfo:{}, // 客户详情页的 客户信息
    total:0,
    loading:false,
    ids:[]
  },

  effects: {
    *fetchList({payload},{call,put}){
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(customerApi.queryCustomerList, payload);
      yield put({
        type: 'saveList',
        payload: response.data || {},
      });
      const jsonData= yield call(customerApi.getCustomerIds,payload);
      yield put({
        type:'saveCustomerIds',
        payload:jsonData.data || []
      })
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },

    *fetchAdd({payload},{call,put}){
      const jsonData= yield call(customerApi.addCustomer,payload);
      return jsonData;
    },
    *fetchApply({payload},{call,put}){
      const jsonData = yield call(customerApi.applyCustomer,payload);
      return jsonData;
    },
    *fetchRemove({payload},{call,put}){
      const jsonData= yield call(customerApi.removeCustomer,payload);
      return jsonData
    },
    *fetchCustomerDetail({payload},{call,put}){
      if(!payload){
        console.warn('客户信息有误');
        return ;
      }
      const jsonData=yield call(customerApi.getCustomerDetail,payload);
      if(jsonData.result){
        let data=jsonData.data || {};
        data.id=payload;
        yield put({
          type:'saveCurrentCustomer',
          payload:data
        })
      }else{
        //有误;
        yield put({
          type:'saveCurrentCustomer',
          payload:{}
        })
      }
    },
    *fetchEditCustomerInfo({payload},{call,put}){
      const jsonData=yield call(customerApi.editCustomerInfo,payload);
      /*if(jsonData.result){
        yield put({
          type:'saveCurrentCustomer',
          payload
        });
      }*/
      return jsonData;
    },
    *allocate({payload},{call,put}){
      const jsonData = yield call(customerApi.allocate,payload);
      return jsonData
    },
    *fetchShift({payload},{call,put}){
      const jsonData = yield call(customerApi.shift,payload);
      return jsonData
    }

  },

  reducers: {
    saveList(state, { payload }) {
      return {
        ...state,
        list:payload.list || [],
        total:payload.total
      };

    },
    changeLoading(state, { payload }) {
      return {
        ...state,
        loading: payload,
      };
    },
    saveCurrentCustomer(state,{payload}){
      return {
        ...state,
        curInfo: payload || {}
      }
    },
    saveCustomerIds(state,{payload}){
      return {
        ...state,
        ids:payload || []
      }
    }
  },
};
